<template>
  <el-container>
    <el-aside width="300px" v-loading="showDicloading">
      <el-container>
        <el-header>
          <el-input
            placeholder="输入关键字进行过滤"
            v-model="dicFilterText"
            clearable
          ></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree
            ref="dictTypeTree"
            class="menu"
            node-key="id"
            :data="dicList"
            :props="dicProps"
            :highlight-current="true"
            default-expand-all="true"
            :expand-on-click-node="false"
            :filter-node-method="dictTypeFilterNode"
            @node-click="dictTypeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <el-tooltip
                  effect="dark"
                  :content="data.dtName"
                  placement="top"
                  :disabled="Boolean(data.dtName.length < 11)"
                >
                  <span class="label">{{ data.dtName }}</span>
                </el-tooltip>
                <span class="code">{{ data.dtType }}</span>

                <span class="do">
                  <el-icon @click.stop="dicEdit(data)"
                    ><el-icon-edit
                  /></el-icon>
                  <el-icon @click.stop="dicDel(node, data)"
                    ><el-icon-delete
                  /></el-icon>
                </span>
              </span>
            </template>
          </el-tree>
        </el-main>
        <el-footer style="height: 51px">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            style="width: 100%"
            @click="add"
            >字典分类</el-button
          >
        </el-footer>
      </el-container>
    </el-aside>

    <el-container class="is-vertical">
      <template v-if="!dictTypeInfo">
        <!-- ###增加了el-main嵌套无数据提示的样式统一 -->
        <el-main style="padding: 20px">
          <el-empty
            description="请选择左侧字典分类"
            :image-size="100"
          ></el-empty>
        </el-main>
      </template>
      <template v-else>
        <el-header>
          <div class="left-panel">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addDict"
            ></el-button>
          </div>
        </el-header>
        <el-main class="nopadding">
          <!-- ###去掉多余样式（宽度和下边距），增加表格高度100%样式，保证表格填满区域，同时也会影响到无数据提示的位置 -->
          <el-table
            :data="dictData"
            height="100%"
            row-key="id"
            default-expand-all
            lazy
            stripe
            :tree-props="{
              children: 'childList',
              hasChildren: true,
            }"
          >
            <el-table-column
              type="index"
              width="50"
              label="序号"
              align="center"
            ></el-table-column>
            <el-table-column
              label="名称"
              prop="dictName"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              label="字典编码"
              prop="dictCode"
              width="250"
            ></el-table-column>
            <el-table-column
              label="排序"
              prop="orderNum"
              width="100"
              align="center"
            ></el-table-column>
            <el-table-column
              label="状态"
              prop="status"
              width="100"
              align="center"
            >
             
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="140"
            >
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="table_edit(scope.row, scope.$index)"
                  >编辑</el-button
                >
                <el-popconfirm
                  title="确定删除吗？"
                  @confirm="dict_del(scope.row)"
                >
                  <template #reference>
                    <el-button type="text" size="small" style="color: #f56c6c"
                      >删除</el-button
                    >
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </template>
    </el-container>
  </el-container>

  <save-drawer
    v-if="drawer.type"
    ref="saveDrawer"
    :title="drawerTitle"
    @onRefreshDictType="onRefreshDictType"
    @closed="drawer.type = false"
  ></save-drawer>

  <save-dict-drawer
    v-if="drawer.dict"
    ref="saveDictDrawer"
    @onRefreshDict="onRefreshDict"
    @closed="drawer.dict = false"
  ></save-dict-drawer>
</template>

<script>
import Sortable from "sortablejs";
import saveDrawer from "./save";
import saveDictDrawer from "./dict/save";

export default {
  name: "dict-index",
  components: {
    saveDrawer,
    saveDictDrawer,
  },
  data() {
    return {
      drawerVisible: false,
      dictTypeInfo: null,
      dtType: "",
      drawer: {
        dict: false,
        type: false,
      },
      dialog: {
        dic: false,
        info: false,
      },
      showDicloading: true,
      dicList: [],
      dicFilterText: "",
      dicProps: {
        children: "childList",
      },
      selection: [],
      dictData: [],
      lastClick: {},
    };
  },
  watch: {
    $route(to, from) {
      if(to.fullPath != "/login"){
        this.getDictType();
        if(this.dictTypeInfo){
          this.getDict(this.dictTypeInfo)
        }
      }
    },
    //监听
    dicFilterText(val) {
      this.$refs.dictTypeTree.filter(val);
    },
  },
  mounted() {
    //渲染后执行
    this.getDictType(); //加载分类数据
    //this.rowDrop()
  },
  methods: {
    //加载分类数据
    async getDictType() {
      let res = await this.$API.dictType.treeData.post();
      if (res.code == 0) {
        this.showDicloading = false;
        if (res.data) {
          this.dicList = res.data;
        } else {
          this.$alert("返回数据格式错误，请尝试刷新", "数据错误", {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            showCancelButton: false,
          });
        }
      } else {
        let errdata = this.$TOOL.response(res);
        this.$alert(
          this.$TOOL.json.get("", errdata, "message"),
          this.$TOOL.json.get("", errdata, "title"),
          {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            showCancelButton: false,
          }
        )
          .then(() => {
            this.showDicloading = false;
          })
          .catch(() => {});
      }
    },
    //加载字典数据
    async getDict(data) {
      this.dictTypeInfo = data;
      let params = { dictType: data.dtType };
      let res = await this.$API.dict.treeData.post(params);
      if (res.code == 0) {
        this.dictData = res.data;
      } else {
        let errdata = this.$TOOL.response(res);
        this.$alert(
          this.$TOOL.json.get("", errdata, "message"),
          this.$TOOL.json.get("", errdata, "title"),
          {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            showCancelButton: false,
          }
        );
      }
    },
    //点击字典分类事件
    async dictTypeClick(data) {
      // 记录上一次点击的字典分类
      this.lastClick = data;
      this.getDict(data);
    },
    //增加字典分类
    add() {
      this.drawerTitle = "添加字典分类";
      this.drawer.type = true;
      this.$nextTick(() => {
        const data = {};
        this.$refs.saveDrawer.open().setData(data);
      });
    },
    //编辑字典分类
    dicEdit(data) {
      this.drawer.type = true;
      this.drawerTitle = "修改字典分类";
      this.$nextTick(() => {
        this.$refs.saveDrawer.open("edit").edit(data.id);
      });
    },
    //删除字典分类
    dicDel(node, data) {
      this.$confirm(`确定删除 ${data.dtName} 项吗？`, "提示", {
        type: "warning",
      })
        .then(async () => {
          this.showDicloading = true;
          let params = { id: data.id };
          let res = await this.$API.dictType.delete.get(params);
          if (res.code == 0) {
            this.$refs.dictTypeTree.remove(data.id);
            this.$message.success("删除成功");
            this.showDicloading = false;
          } else {
            let errdata = this.$TOOL.response(res);
            this.$alert(
              this.$TOOL.json.get("", errdata, "message"),
              this.$TOOL.json.get("", errdata, "title"),
              {
                type: "error",
                confirmButtonText: "确定",
                dangerouslyUseHTMLString: true,
                showCancelButton: false,
              }
            )
              .then(() => {
                this.showDicloading = false;
              })
              .catch(() => {});
          }
        })
        .catch(() => {});
    },
    //刷新字典分类
    onRefreshDictType() {
      this.getDictType();
    },
    //刷新字典
    onRefreshDict() {
      this.getDict(this.lastClick);
    },
    //树过滤
    dictTypeFilterNode(value, data) {
      if (!value) return true;
      let targetText = data.dtName + data.dtType;
      return targetText.indexOf(value) !== -1;
    },
    //行拖拽
    rowDrop() {
      const _this = this;
      const tbody = this.$refs.table.$el.querySelector(
        ".el-table__body-wrapper tbody"
      );
      Sortable.create(tbody, {
        handle: ".move",
        animation: 300,
        ghostClass: "ghost",
        onEnd({ newIndex, oldIndex }) {
          const tableData = _this.$refs.table.tableData;
          const currRow = tableData.splice(oldIndex, 1)[0];
          tableData.splice(newIndex, 0, currRow);
          _this.$message.success("排序成功");
        },
      });
    },
    //添加字典
    addDict() {
      this.drawerDictTitle = "添加字典";
      // let dictType = this.$TOOL.json.get("", this.dictTypeInfo, "dtType");
      // let dictType = "systemType"
      console.log("this.dictTypeInfo.dtType",this.dictTypeInfo.dtType);
      let dictType = this.dictTypeInfo.dtType;
      if (dictType == "") {
        this.$message.warning("请选择字典分类");
        return false;
      }
      this.drawer.dict = true;
      this.$nextTick(() => {
        const data = { dictType: dictType };
        this.$refs.saveDictDrawer.open().setData(data);
      });
    },
    //编辑字典
    table_edit(row) {
      this.drawer.dict = true;
      this.$nextTick(() => {
        this.$refs.saveDictDrawer.open("edit").edit(row.id);
      });
    },
    //删除明细
    async dict_del(row) {
      let reqData = { id: row.id };
      let res = await this.$API.dict.delete.get(reqData);
      if (res.code == 0) {
        let params = { dictType: row.dictType };
        let res2 = await this.$API.dict.treeData.post(params);
        this.dictData = res2.data;
        this.$message.success("删除成功");
      } else {
        let errdata = this.$TOOL.response(res);
        this.$alert(
          this.$TOOL.json.get("", errdata, "message"),
          this.$TOOL.json.get("", errdata, "title"),
          {
            type: "error",
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true,
            showCancelButton: false,
          }
        );
      }
    },
    //批量删除
    async batch_del() {
      this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, "提示", {
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading();
          this.selection.forEach((item) => {
            this.$refs.table.tableData.forEach((itemI, indexI) => {
              if (item.id === itemI.id) {
                this.$refs.table.tableData.splice(indexI, 1);
              }
            });
          });
          loading.close();
          this.$message.success("操作成功");
        })
        .catch(() => {});
    },

    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection;
    },
    //表格内开关事件
    changeSwitch(val, row) {
      //1.还原数据
      row.yx = row.yx == "1" ? "0" : "1";
      //2.执行加载
      row.$switch_yx = true;
      //3.等待接口返回后改变值
      setTimeout(() => {
        delete row.$switch_yx;
        row.yx = val;
        this.$message.success(`操作成功id:${row.id} val:${val}`);
      }, 500);
    },
    //根据ID获取树结构
    filterTree(id) {
      let target = null;
      function filter(tree) {
        tree.forEach((item) => {
          if (item.id == id) {
            target = item;
          }
          if (item.childList) {
            filter(item.childList);
          }
        });
      }
      if (this.$refs.table.tableData && this.$refs.table.tableData > 0) {
        filter(this.$refs.table.tableData);
      }

      return target;
    },
  },
};
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 24px;
  height: 100%;
}
.custom-tree-node {
  width: calc(100% - 50px);
}
.custom-tree-node .label {
  align-items: center;
  display: block;
  width: calc(100% - 20px);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  -webkit-line-clamp: 1;
}
.custom-tree-node .code {
  font-size: 12px;
  color: #999;
}
.custom-tree-node .do {
  display: none;

  /* position: absolute;
  right: 15px;
  width: 50px;
  text-align: right; */
}
.custom-tree-node .do i {
  margin-left: 5px;
  color: #999;
  padding: 5px;
  font-size: 24px;
  margin-top: 5px;
}
.custom-tree-node .do i:hover {
  color: #333;
}
.custom-tree-node:hover .code {
  display: none;
}
.custom-tree-node:hover .do {
  display: inline-block;
}
.el-table--border {
  border: none;
}
.nopadding:deep(.el-table__body-wrapper) {
  height: 700px;
}
</style>
